package com.spider.im.chat.message.login;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.protobuf.Parser;
import com.spider.im.chat.annotation.MessageTypeHandler;

import com.spider.im.chat.message.AbstractMessageStrategy;
import com.spider.im.chat.proto.ChatProto;
import com.spider.im.user.entity.User;
import com.spider.im.user.service.UserService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@MessageTypeHandler(type = ChatProto.MessageType.LOGIN)
public class LoginStrategy extends AbstractMessageStrategy<ChatProto.LoginRequest> {

    @Resource
    public RedissonClient redissonClient;

    @Resource
    public UserService userService;


    @Override
    public Parser<ChatProto.LoginRequest> getParser() {
        return ChatProto.LoginRequest.parser();
    }

    /**
     * 处理登录请求
     * @param ctx
     * @param message
     */
    @Override
    public void handle(ChannelHandlerContext ctx, ChatProto.LoginRequest message) {
        String username = message.getUsername();
        String password = message.getPassword();
        Channel channel = ctx.channel();
        log.info("用户登录: {}", message.getUsername());
        boolean success = false;
        String messageR = "登陆成功";
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (user == null) {
            messageR = "用户不存在";
            ChatProto.MessageWrapper wrapper = getMessageWrapper(success, messageR);
            this.sendResponse(channel, wrapper);
           log.error("用户不存在 {}", username);
           return;
        }
        String token = user.getUsername();
       activeChannels.put(user.getId(), channel);

       //TODO 登陆逻辑
        success = true;
        ChatProto.MessageWrapper wrapper = getMessageWrapper(success, messageR);
        this.sendResponse(channel, wrapper);
        log.info("用户:{},token:{}登录成功", message.getUsername(),token);
    }

    /**
     * 构建消息包装
     *
     * @return
     */
    private static ChatProto.MessageWrapper getMessageWrapper(boolean success, String message) {
        ChatProto.Response response = ChatProto.Response.newBuilder()
                .setSuccess(success)
                .setMessage(message)
                .build();
        return ChatProto.MessageWrapper.newBuilder()
                .setType(ChatProto.MessageType.LOGIN)
                .setPayload(response.toByteString())
                .build();
    }
}
